<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2018/12/17
 * Time: 下午5:39
 */

namespace App\Tools;

use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;
use Illuminate\Support\Facades\Log;

class Oss
{
    private $accesskeyid;
    private $accesskeysecret;
    private $endpoint;
    private $bucket;

    public function __construct(){
        $this->accesskeyid = config("oss.accesskeyid");
        $this->accesskeysecret = config("oss.accesskeysecret");
        $this->endpoint = config("oss.endpoint");
        $this->bucket = config("oss.bucket");
    }

    public function getClient(){
        static $ossClient;
        if (empty($ossClient)){
            $ossClient = new OssClient($this->accesskeyid, $this->accesskeysecret, $this->endpoint, false);
        }
        return $ossClient;
    }

    /**
     * 生成客户端上传图片的临时url
     * @param $uri     oss上的路径 users/pic/1212/600eeac2b13fb7a597004e1f216840e2.png
     * @return string  客户端上传的的零时url
     */
    public function get_object_put_url($uri){
        $timeout = 3600;
        try {
            $ossClient = $this->getClient();
            $signedUrl = $ossClient->signUrl($this->bucket, $uri, $timeout, "PUT");

        } catch (OssException $e) {
            //printf(__FUNCTION__ . ": FAILED\n");
            //printf($e->getMessage() . "\n");
            return "";
        }
        return $signedUrl;
    }


    public function frozenObject($uri)
    {
        if ($uri[0] == '/'){
            $uri = ltrim($uri, '/');
        }
        try {
            $ossClient = $this->getClient();
            $ossClient->putObjectAcl($this->bucket, $uri, 'private');
        } catch (OssException $e) {
            //printf(__FUNCTION__ . ": FAILED\n");
            //    printf($e->getMessage() . "\n");
            return false;
        }
        return true;
    }

	/**
	 * 删除对象
	 * @param string $sPath
	 * @return bool
	 */
	public function deleteObject($sPath) {
		if(empty($sPath)) {
			return false;
		}

		try {
			$ossClient = $this->getClient();
			$res = $ossClient->deleteObject($this->bucket, $sPath);
            Log::info('del_oss_opus-'.$sPath, [$res]);
			return true;
		} catch(OssException $E) {
            Log::info('del_oss_opus-'.$sPath, [$E->getMessage()]);
			return false;
		}
	}

    /**
     * 批量删除对象
     * @param string $sPath
     * @return bool
     */
    public function batchDeleteObject($paths) {
        if(empty($paths)) {
            return false;
        }

        try {
            $ossClient = $this->getClient();
            $res = $ossClient->deleteObjects($this->bucket, $paths);
            Log::info('del_bath_oss_opus-', [$res]);
            return true;
        } catch(OssException $E) {
            Log::info('del_bath_oss_opus-', [$E->getMessage()]);
            return false;
        }
    }
}